package thesis.filesharing.web.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import thesis.filesharing.bo.DocumentFileBO;
import thesis.filesharing.bo.SemesterBO;
import thesis.filesharing.bo.StudentBO;
import thesis.filesharing.model.Clazz;
import thesis.filesharing.model.DocumentFile;
import thesis.filesharing.web.auth.AuthUtil;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@Controller
public class DownloadFileController {
	
	@Autowired
	private StudentBO studentBO;
	
	@Autowired
	private DocumentFileBO documentFileBO;
	
	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	
	@Autowired
	private SemesterBO semesterBO;
	
	@PreAuthorize("hasRole('ROLE_STUDENT')")
	@RequestMapping(value = "/student/downloadDocument", method = RequestMethod.GET)
	public String downloadDocument(@RequestParam(value = "key", required = false) String key, ModelMap model) {
		String studentId = AuthUtil.getCurrentAuthenticatedUsername();
		Integer semester = semesterBO.getCurrentSemester().getSemesterName();
		if (studentId != null && semester != null) {
			List<Clazz> registeredClasses = studentBO.listClassesStudentRegistered(studentId, semester);
			model.addAttribute("registeredClasses", registeredClasses);
		}
		if (key != null && !"NONE".equalsIgnoreCase(key)) {
			Key classKey = KeyFactory.stringToKey(key);
			model.addAttribute("documentFiles", documentFileBO.listDocumentFilesOfClass(classKey));
		}
		
		return "student/downloadDocument";
	}
	
	@PreAuthorize("hasRole('ROLE_STUDENT')")
	@RequestMapping(value = "/student/processDownloadDocument", method = RequestMethod.GET)
	public void processDownloadDocument(@RequestParam(value = "key", required = true) String key,
			HttpServletResponse response) throws IOException {
		DocumentFile file = documentFileBO.findDocumentFile(KeyFactory.stringToKey(key));
		if (file != null) {
			BlobKey blobKey = new BlobKey(file.getDocumentFileBlobKey());
			response.setContentType(file.getDocumentFileMime());
			response.setHeader("Content-Disposition", "attachment;filename=" + file.getDocumentFileName());
			blobstoreService.serve(blobKey, response);
		}
	}
}
